from django.db import models
import datetime
from time import strftime

class TimestampField(models.DateTimeField):
    """
    """
    def __init__(self, null=False, blank=False, auto_created=True, auto_update=False, **kwargs):
        super(TimestampField, self).__init__(**kwargs)
        self.blank, self.isnull = blank, null
        self.null = False
        self.auto_created = auto_created
        self.auto_update = auto_update

    def db_type(self, connection):
        typ=['TIMESTAMP']
        if self.isnull:
            typ += ['NULL']
        if self.auto_created:
            typ += ['default CURRENT_TIMESTAMP']
        if self.auto_update:
            typ += ['on update CURRENT_TIMESTAMP']
        return ' '.join(typ)

    def to_python(self, value):
        if isinstance(value, int):
            return datetime.fromtimestamp(value)
        else:
            return models.DateTimeField.to_python(self, value)

    def get_db_prep_value(self, value, connection, prepared=False):
        if value==None:
            return None
        return strftime('%Y-%m-%d %H:%M:%S',value.timetuple())
